// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:42
describe: 飞书即时通讯相关功能
*/

use crate::fsa::base::{request, FeishuApiBase};
use loguru::logger;
use serde_json::Value;

/// 飞书即时通讯类
pub struct IM {
    base: FeishuApiBase,
}

impl IM {
    pub fn new(app_id: &str, app_secret: &str) -> Self {
        Self {
            base: FeishuApiBase::new(app_id, app_secret),
        }
    }
    
    /// 根据手机号获取用户ID
    pub async fn get_user_id(&mut self, mobiles: &[String]) -> Result<Value, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id";
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "mobiles": mobiles
        });
        request("POST", url, &headers, Some(&payload)).await
    }
    
    /// 发送文本消息
    pub async fn send_text(&mut self, text: &str, receive_id: &str, receive_id_type: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/im/v1/messages";
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "receive_id": receive_id,
            "msg_type": "text",
            "content": {
                "text": text
            }
        });
        
        let mut query_params = format!("?receive_id_type={}", receive_id_type);
        let full_url = format!("{}{}", url, query_params);
        
        request("POST", &full_url, &headers, Some(&payload)).await
    }
    
    /// 发送图片消息
    pub async fn send_image(&mut self, image_key: &str, receive_id: &str, receive_id_type: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/im/v1/messages";
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "receive_id": receive_id,
            "msg_type": "image",
            "content": {
                "image_key": image_key
            }
        });
        
        let mut query_params = format!("?receive_id_type={}", receive_id_type);
        let full_url = format!("{}{}", url, query_params);
        
        request("POST", &full_url, &headers, Some(&payload)).await
    }
    
    /// 发送文件消息
    pub async fn send_file(&mut self, file_key: &str, receive_id: &str, receive_id_type: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/im/v1/messages";
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "receive_id": receive_id,
            "msg_type": "file",
            "content": {
                "file_key": file_key
            }
        });
        
        let mut query_params = format!("?receive_id_type={}", receive_id_type);
        let full_url = format!("{}{}", url, query_params);
        
        request("POST", &full_url, &headers, Some(&payload)).await
    }
    
    /// 发送卡片消息
    pub async fn send_card(&mut self, card: &Value, receive_id: &str, receive_id_type: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/im/v1/messages";
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "receive_id": receive_id,
            "msg_type": "interactive",
            "content": card
        });
        
        let mut query_params = format!("?receive_id_type={}", receive_id_type);
        let full_url = format!("{}{}", url, query_params);
        
        request("POST", &full_url, &headers, Some(&payload)).await
    }
    
    /// 上传图片
    pub async fn upload_image(&mut self, image_path: &str) -> Result<String, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/im/v1/files";
        let headers = self.base.get_headers().await?;
        
        // 读取图片文件
        let image_content = std::fs::read(image_path)?;
        let image_name = std::path::Path::new(image_path)
            .file_name()
            .unwrap()
            .to_str()
            .unwrap();
        
        let payload = serde_json::json!({
            "type": "image",
            "name": image_name,
            "size": image_content.len(),
            "content": base64::encode(&image_content)
        });
        
        let resp = request("POST", url, &headers, Some(&payload)).await?;
        Ok(resp["data"]["image_key"].as_str().unwrap().to_string())
    }
    
    /// 上传文件
    pub async fn upload_file(&mut self, file_path: &str) -> Result<String, Box<dyn std::error::Error>> {
        let url = "https://open.feishu.cn/open-apis/im/v1/files";
        let headers = self.base.get_headers().await?;
        
        // 读取文件
        let file_content = std::fs::read(file_path)?;
        let file_name = std::path::Path::new(file_path)
            .file_name()
            .unwrap()
            .to_str()
            .unwrap();
        
        let payload = serde_json::json!({
            "type": "file",
            "name": file_name,
            "size": file_content.len(),
            "content": base64::encode(&file_content)
        });
        
        let resp = request("POST", url, &headers, Some(&payload)).await?;
        Ok(resp["data"]["file_key"].as_str().unwrap().to_string())
    }
} 